<template>
  <div class="map-wrapper">
    <div class="search-box" v-if="editable">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索地点"
        size="small"
        @keyup.enter.native="handleSearch"
      >
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>
    </div>
    <div class="map-container" ref="mapContainer"></div>
  </div>
</template>

<script>
export default {
  name: 'BaiduMap',
  props: {
    // 经度
    longitude: {
      type: [Number, String],
      default: 116.404
    },
    // 纬度
    latitude: {
      type: [Number, String],
      default: 39.915
    },
    // 缩放级别
    zoom: {
      type: Number,
      default: 15
    },
    // 是否允许编辑（拖动标记点）
    editable: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      map: null,
      marker: null,
      BMap: null,
      searchKeyword: '',
      localSearch: null,
      geocoder: null  // 添加地理编码器
    }
  },
  mounted() {
    this.initMap()
  },
  methods: {
    initMap() {
      // 确保百度地图脚本已加载
      if (typeof BMap === 'undefined') {
        const script = document.createElement('script')
        script.src = `https://api.map.baidu.com/api?v=3.0&ak=${process.env.VUE_APP_BAIDU_MAP_AK}&callback=initBaiduMap`
        document.body.appendChild(script)
        window.initBaiduMap = () => {
          this.initMapInstance()
        }
      } else {
        this.initMapInstance()
      }
    },
    initMapInstance() {
      this.BMap = BMap
      this.map = new BMap.Map(this.$refs.mapContainer, {
        enableMapClick: false,  // 禁用地图默认的点击事件
        mapType: BMAP_NORMAL_MAP
      })
      const point = new BMap.Point(this.longitude, this.latitude)
      this.map.centerAndZoom(point, this.zoom)
      
      // 添加地图控件
      this.map.addControl(new BMap.ScaleControl())
      this.map.enableScrollWheelZoom()

      // 添加标记点
      this.marker = new BMap.Marker(point, {
        enableClicking: false  // 禁用标记点的点击事件
      })
      this.map.addOverlay(this.marker)

      if (this.editable) {
        // 允许拖动标记点
        this.marker.enableDragging()
        this.marker.addEventListener('dragend', (e) => {
          this.$emit('marker-move', {
            longitude: e.point.lng,
            latitude: e.point.lat
          })
        })

        // 初始化本地搜索
        this.localSearch = new BMap.LocalSearch(this.map, {
          onSearchComplete: (results) => {
            if (results.getNumPois()) {
              const firstPoi = results.getPoi(0)
              const point = firstPoi.point
              this.marker.setPosition(point)
              this.map.panTo(point)
              this.$emit('marker-move', {
                longitude: point.lng,
                latitude: point.lat
              })
            }
          }
        })
      }

      // 点击地图更新标记点位置
      this.map.addEventListener('click', (e) => {
        if (this.editable) {
          const point = new BMap.Point(e.point.lng, e.point.lat)
          this.marker.setPosition(point)
          this.$emit('marker-move', {
            longitude: e.point.lng,
            latitude: e.point.lat
          })
        }
      })
    },
    handleSearch() {
      if (this.searchKeyword && this.localSearch) {
        this.localSearch.search(this.searchKeyword)
      }
    },
    // 地理编码：地址转换为经纬度
    geocodeAddress(address) {
      if (!address) return;
      
      if (!this.geocoder) {
        this.geocoder = new BMap.Geocoder();
      }
      
      this.geocoder.getPoint(address, (point) => {
        if (point) {
          this.marker.setPosition(point);
          this.map.panTo(point);
          this.$emit('marker-move', {
            longitude: point.lng,
            latitude: point.lat
          });
        }
      });
    }
  },
  watch: {
    longitude(newVal) {
      if (this.marker && this.BMap) {
        const point = new this.BMap.Point(newVal, this.latitude)
        this.marker.setPosition(point)
        this.map.panTo(point)
      }
    },
    latitude(newVal) {
      if (this.marker && this.BMap) {
        const point = new this.BMap.Point(this.longitude, newVal)
        this.marker.setPosition(point)
        this.map.panTo(point)
      }
    }
  }
}
</script>

<style scoped>
.map-wrapper {
  width: 100%;
  height: 100%;
  min-height: 400px;
  position: relative;
  background-color: #f5f5f5;
}

.map-container {
  width: 100%;
  height: 100%;
  min-height: 400px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.search-box {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 300px;
  z-index: 9999;
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  pointer-events: auto;
}

.search-box :deep(.el-input__inner) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.search-box :deep(.el-input-group__append) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: white;
  padding: 0 15px;
}

.search-box :deep(.el-input-group__append:hover) {
  background-color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-3);
}

/* 隐藏百度地图Logo和版权信息 */
:deep(.anchorBL) {
  display: none !important;
}

/* 隐藏左上角的按钮组 */
:deep(.BMap_stdMpCtrl) {
  display: none !important;
}

/* 隐藏右下角的缩放控件 */
:deep(.BMap_omCtrl) {
  display: none !important;
}
</style> 